<template>
  <div class="wechat-main">
    <!-- 左侧：会话/好友列表 -->
    <div class="sidebar">
      <div class="sidebar-header">
        <input v-model="search" placeholder="搜索" class="search-input" />
        <button class="add-btn">+</button>
      </div>
      <ul class="session-list">
        <li
          v-for="session in filteredSessions"
          :key="session.id"
          :class="['session-item', activeSession && activeSession.id === session.id ? 'active' : '']"
          @click="selectSession(session)"
        >
          <img :src="session.avatar" class="avatar" />
          <div class="session-info">
            <div class="session-title">
              <span class="nickname">{{ session.nickname }}</span>
              <span class="time">{{ formatTime(session.lastTime) }}</span>
            </div>
            <div class="session-last">
              <span>{{ session.lastMessage }}</span>
              <span v-if="session.unreadCount > 0" class="unread-dot"></span>
            </div>
          </div>
        </li>
      </ul>
    </div>
    <!-- 右侧：聊天窗口 -->
    <div class="chat-panel">
      <ChatWindow v-if="activeSession" :chatUser="activeSession" />
      <div v-else class="empty-chat">请选择一个会话开始聊天</div>
    </div>
  </div>
</template>

<script>
import ChatWindow from './ChatWindow.vue'
import axios from 'axios'

export default {
  components: { ChatWindow },
  data() {
    return {
      friends: [],
      sessions: [],
      activeSession: null,
      search: ''
    }
  },
  computed: {
    filteredSessions() {
      if (!this.search) return this.sessions
      return this.sessions.filter(s =>
        s.nickname.includes(this.search)
      )
    }
  },
  async created() {
    await this.loadFriends()
    await this.loadSessions()
    // created时主动处理一次
    this.handleFriendId(this.$route.query.friendId)
  },
  watch: {
    '$route.query.friendId': {
      immediate: false, // created里已主动调用
      handler(friendId) {
        this.handleFriendId(friendId)
      }
    }
  },
  methods: {
    async loadFriends() {
      const userId = localStorage.getItem('userId')
      const res = await axios.get('/api/friend/list', { params: { userId } })
      this.friends = res.data
    },
    async loadSessions() {
      const userId = localStorage.getItem('userId')
      const res = await axios.get('/api/session/list', { params: { userId } })
      this.sessions = res.data
    },
    selectSession(session) {
      this.activeSession = session
    },
    formatTime(time) {
      if (!time) return ''
      const d = new Date(time)
      return d.getHours() + ':' + (d.getMinutes() < 10 ? '0' : '') + d.getMinutes()
    },
    handleFriendId(friendId) {
      if (!friendId) return
      // 1. 查找会话
      let session = this.sessions.find(s => String(s.id) === String(friendId))
      if (!session) {
        // 2. 没有会话，查找好友
        let friend = this.friends.find(f => String(f.id) === String(friendId))
        if (!friend) {
          friend = { id: friendId, nickname: '新好友', avatar: '' }
        }
        session = {
          id: friend.id,
          nickname: friend.nickname,
          avatar: friend.avatar,
          lastMessage: '',
          lastTime: '',
          unreadCount: 0
        }
        this.sessions.unshift(session)
      }
      // 3. 高亮选中
      this.activeSession = session
    }
  }
}
</script>

<style scoped>
.wechat-main { display: flex; height: 600px; background: #f7f7f7; border-radius: 8px; box-shadow: 0 2px 8px #eee; }
.sidebar { width: 280px; background: #ededed; display: flex; flex-direction: column; }
.sidebar-header { display: flex; align-items: center; padding: 10px; }
.search-input { flex: 1; border: none; border-radius: 4px; padding: 6px 10px; }
.add-btn { margin-left: 8px; width: 32px; height: 32px; border: none; background: #fff; border-radius: 50%; font-size: 20px; cursor: pointer; }
.session-list { flex: 1; overflow-y: auto; margin: 0; padding: 0; list-style: none; }
.session-item { display: flex; align-items: center; padding: 10px 16px; cursor: pointer; border-bottom: 1px solid #e4e4e4; transition: background 0.2s; }
.session-item.active, .session-item:hover { background: #d6f5d6; }
.avatar { width: 44px; height: 44px; border-radius: 8px; margin-right: 12px; }
.session-info { flex: 1; }
.session-title { display: flex; justify-content: space-between; }
.nickname { font-weight: bold; }
.time { color: #888; font-size: 12px; }
.session-last { display: flex; justify-content: space-between; color: #888; font-size: 13px; margin-top: 4px; }
.unread-dot { display: inline-block; width: 8px; height: 8px; background: #fa5151; border-radius: 50%; margin-left: 6px; }
.chat-panel { flex: 1; background: #f7f7f7; position: relative; }
.empty-chat { color: #aaa; text-align: center; margin-top: 100px; }
</style>